import { ILoadingService } from 'ibz-core';

/**
 * @description 应用加载服务
 * @export
 * @class AppLoadingService
 * @implements {ILoadingService}
 */
export class AppLoadingService implements ILoadingService {
  /**
   * @description 应用加载服务实例
   * @private
   * @static
   * @type {AppLoadingService}
   * @memberof AppLoadingService
   */
  private static instance: AppLoadingService;

  /**
   * @description 获取应用加载服务实例
   * @static
   * @return {*}
   * @memberof AppLoadingService
   */
  public static getInstance(): AppLoadingService {
    if (!this.instance) {
      this.instance = new AppLoadingService();
    }
    return this.instance;
  }

  /**
   * @description loading 对象
   * @type {*}
   * @memberof AppLoadingService
   */
  private elLoadingComponent: any;

  /**
   * @description 是否加载
   * @type {boolean}
   * @memberof AppLoadingServiceBase
   */
  private isLoading: boolean = false;

  /**
   * @description 统计加载
   * @type {number}
   * @memberof AppAppLoadingService
   */
  private loadingCount: number = 0;

  /**
   * @description 加载结束
   * @memberof AppLoadingService
   */
  public endLoading(): void {
    const endLoading = (selector: any) => {
      if (!this.isLoading) {
        return;
      }
      if (selector) {
        const loadMask = selector.querySelector('.loading-container');
        if (loadMask && selector.contains(loadMask)) {
          selector.removeChild(loadMask);
        }
      }
      this.isLoading = false;
    };

    const body = document.querySelector('body');
    if (this.loadingCount > 0) {
      this.loadingCount--;
    }
    if (this.loadingCount === 0) {
      endLoading(body);
    }
  }

  /**
   * @description 应用开始加载
   * @memberof AppLoadingService
   */
  public beginLoading() {
    const beginLoading = (selector: any) => {
      this.isLoading = true;
      // 自定义loading元素
      const userEle = document.createElement('div');
      userEle.classList.add('loading-container');
      const innerDiv = document.createElement('div');
      innerDiv.classList.add('loading');
      for (let i = 0; i < 4; i++) {
        const dot = document.createElement('span');
        innerDiv.appendChild(dot);
      }
      userEle.appendChild(innerDiv);
      // 挂载
      if (selector) {
        selector.appendChild(userEle);
      }
    };

    const body = document.querySelector('body');
    if (this.loadingCount === 0) {
      beginLoading(body);
    }
    this.loadingCount++;
  }
}
